<!--
Copyright (C) 2021 Ciro Cattuto <ciro.cattuto@gmail.com>

The MIT License (MIT)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-->

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="../../dist/dap.umd.js"></script>
        <script src="rtt.js"></script>
        <link rel="stylesheet" href="xterm.css" />
        <script src="xterm.js"></script>
        <style>
            button {
                display: inline-block;
                padding: 0.3em 1.2em;
                margin: 0 0.1em 0.1em 0;
                border-radius: 2em;
                border:0.16em solid rgba(255,255,255,0);
                box-sizing: border-box;
                color:white;
                text-align: center;
                background-color:rgb(148, 13, 125)
            }
        </style>
    </head>
    
<body>
    <button id="control">start RTT</button>

    <div id="terminal"></div>

    RTT terminal demo. Click button to connect / disconnect. Terminal input is sent on enter.

    <script>
        // WebUSB and DAP
        var device = null;
        var transport = null;
        var processor = null;
        var rtt = null;

        // terminal
        var term = null;
        var line_input = "";
        var cmd = "";

        // control
        var connected = false;

        // start/stop button
        document.getElementById("control").onclick = async () => {
            if (!connected) {
                // locate debug probe
                try {
                    device = await navigator.usb.requestDevice({
                        filters: [ {vendorId: 0xD28} ]
                    });
                } catch (err) {
                    return
                };

                transport = new DAPjs.WebUSB(device);
                processor = new DAPjs.CortexM(transport);

                // connect to target and reset it
                await processor.connect();
                await processor.softReset();
                await new Promise(resolve => setTimeout(resolve, 1000));
                await processor.halt();
                console.log('Connected.');

                // locate RTT buffers
                rtt = new RTT(processor);
                numBufs = await rtt.init();
                if (numBufs < 0)
                    return;
                console.log("RTT up buffers:", rtt.bufUp);
                console.log("RTT down buffers:", rtt.bufDown);
                await processor.resume();

                document.getElementById("control").innerHTML = 'stop RTT';
                connected = true;
            } else {
                connected = false;
                rtt = null;
                await processor.disconnect();
                await transport.close();
                await device.close();
                term.reset();
                document.getElementById("control").innerHTML = 'start RTT';
                console.log('Disconnected.');
            }
        };

        // process terminal keystroke
        function processKey (e) {
            if (!connected)
                return;

            const ev = e.domEvent;
            const printable = !ev.altKey && !ev.ctrlKey && !ev.metaKey;

            if (ev.keyCode === 13) { // process newline
                term.write('\r\n');
                cmd = line_input + "\r\n";
                console.log('sending: \"' + line_input + '\"');
                line_input = "";
            } else if (ev.keyCode === 8) { // process backspace
                if (term._core.buffer.x > 0) {
                    term.write('\b \b');
                    line_input = line_input.slice(0,-1);
                }
            } else if (printable) { // printable chars
                term.write(e.key);
                line_input += e.key;
            }
        }

        // main loop
        async function mainLoop () {
            // set up terminal
            term = new Terminal();
            term.setOption("theme", {
                background: "#202B33",
                foreground: "#F5F8FA"
            });
            term.onKey(processKey);
            term.open(document.getElementById('terminal'));
            term.reset();
            

            while (true) {
                if (!connected) {
                    await new Promise(resolve => setTimeout(resolve, 100));
                    continue;
                }

                // read from target
                msg = await rtt.read(0);
                if (msg.length > 0) {
                    term.write( new TextDecoder().decode(msg) );
                }
                
                // send to target
                if (cmd.length) {
                    cmdBytes = new TextEncoder().encode(cmd);
                    ret = await rtt.write(0, cmdBytes);
                    if (ret < 0)
                        console.log("cannot write", cmdBytes, "chars");
                    cmd = "";
                }

                await new Promise(resolve => setTimeout(resolve, 1));
            }
        }

        mainLoop();

    </script>
</body>
</html>
